package com.tencreat.common.service.impl;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencreat.common.core.enums.ImOnlineStatus;
import com.tencreat.common.core.enums.ImSessionType;
import com.tencreat.common.core.enums.ImUserStatus;
import com.tencreat.common.entity.*;
import com.tencreat.common.entity.vo.UserAddVo;
import com.tencreat.common.mapper.ImUserMapper;
import com.tencreat.common.service.ImSessionService;
import com.tencreat.common.service.ImSettingService;
import com.tencreat.common.service.ImUserService;
import com.tencreat.common.service.ImUserSessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ImUserServiceImpl extends ServiceImpl<ImUserMapper, ImUser> implements ImUserService {
    @Autowired
    ImSessionService sessionService;
    @Autowired
    ImUserSessionService userSessionService;
    @Autowired
    ImSettingService settingService;

    @Transactional
    @Override
    public ImUserSession newUser(ImUser imUser) {
        ImUserSession result;
        //判断是否已经注册
        ImUser one = getById(imUser.getId());

        ImSettingBackground setting = settingService.getBackGroundSetting();
        // 管理员
        ImUser admin = getById(1);
        if(null == one){
            //注册一个用户
            imUser.setNickname(imUser.getUsername());
            imUser.setAvatar(setting.getUserAvatar());
            imUser.setOnlineStatus(ImOnlineStatus.ONLINE);
            imUser.setUserStatus(ImUserStatus.NORMAL);
            save(imUser);

            // 发起两个用户的会话
            result = sessionService.newSession(imUser, admin);
        }else{
            // 获的和管理员的session
            return userSessionService.lambdaQuery().eq(ImUserSession::getUserId, one.getId())
                    .eq(ImUserSession::getToId, admin.getId())
                    .last("limit 1").one();
        }
        return result;
    }
}
